package cn.ezios.huo.s3.bean;

import lombok.*;
import lombok.experimental.Accessors;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Setter
@Getter
@ToString
@Accessors(chain = true)
@NoArgsConstructor
public class HuoStorageDto {

    private String bucket;

    private String path = HuoStorageEnum.nemo.name();

    private String fileName;

    public String key(){
        return path + "/" + fileName;
    }

    private String localDate(){
        return LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE).replace("-","/");
    }
    private String localDate(HuoStorageEnum enu){
        return enu.name() + "/" + localDate();
    }

    /**
     * 一般情况
     * @param bucket
     * @param fileName
     */
    public HuoStorageDto(String bucket, String fileName) {
        this.bucket = bucket;
        this.fileName = fileName;
        this.path = localDate();
    }

    /**
     * 自定义key前缀
     * @param bucket
     * @param keyPrefix
     * @param fileName
     */
    public HuoStorageDto(String bucket, HuoStorageEnum keyPrefix, String fileName) {
        this.bucket = bucket;
        this.fileName = fileName;

        String template = "%s/%s";
        this.path = String.format(template,keyPrefix,localDate());
    }

    public static HuoStorageDto create(){
        return new HuoStorageDto();
    }
    public static HuoStorageDto create(String bucket){
        return new HuoStorageDto().setBucket(bucket);
    }
    public static HuoStorageDto create(String bucket,String fileName){
        HuoStorageEnum enu = pathChoose(fileName);
        return new HuoStorageDto().setBucket(bucket).setFileName(fileName).localDatePath(enu);
    }

    public HuoStorageDto localDatePath(){
        path = localDate();
        return this;
    }
    public HuoStorageDto localDatePath(HuoStorageEnum enu){
        path = localDate(enu);
        return this;
    }

    public HuoStorageDto customPath(String key){
        this.path = key;
        return this;
    }

    public HuoStorageDto definePath(HuoStorageEnum enu){
        this.path = enu.name();
        return this;
    }
    public static HuoStorageEnum pathChoose(String fileName){
        String[] document = new String[]{"doc","docx","ppt","pptx","pdf"};
        String[] image = new String[]{"jpg","jpeg","png","gif","bmp","webp"};
        String[] table = new String[]{"csv","tsv","txt","xls","xlsx",};

        for (String type : document) {
            if(fileName.endsWith(type)){
                return HuoStorageEnum.document;
            }
        }
        for (String type : image) {
            if(fileName.endsWith(type)){
                return HuoStorageEnum.image;
            }
        }
        for (String type : table) {
            if(fileName.endsWith(type)){
                return HuoStorageEnum.table;
            }
        }
        return HuoStorageEnum.tmp;
    }
}
